package org.jsola.hr.service.impl;

import org.jsola.core.Page;
import org.jsola.hr.common.ExampleKit;
import org.jsola.hr.constant.HrConstants;
import org.jsola.hr.dao.IEmpWorkRequireDAO;
import org.jsola.hr.dto.EmpWorkRequireAddDTO;
import org.jsola.hr.dto.EmpWorkRequireUpdateDTO;
import org.jsola.hr.entity.CompanyDO;
import org.jsola.hr.entity.EmpWorkRequireDO;
import org.jsola.hr.query.EmpWorkRequireQuery;
import org.jsola.hr.service.ICompanyService;
import org.jsola.hr.service.IEmpWorkRequireService;
import org.jsola.hr.vo.EmpWorkRequireListVO;
import org.jsola.hr.vo.EmpWorkRequireVO;
import org.jsola.user.core.TokenUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author zhr
 */
@Service("hrEmpWorkRequireServiceImpl")
public class EmpWorkRequireServiceImpl implements IEmpWorkRequireService {

    @Autowired
    private IEmpWorkRequireDAO empWorkRequireDAO;

    @Autowired
    private ICompanyService companyService;

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public EmpWorkRequireVO save(EmpWorkRequireAddDTO empWorkRequireAddDTO, TokenUser tokenUser) {
        // 校验是否存在
        EmpWorkRequireVO requireVO = findByCompanyAndType(
                empWorkRequireAddDTO.getCompanyId(),
                empWorkRequireAddDTO.getRequireType(),
                tokenUser.getSiteId());
        if (!Objects.isNull(requireVO)) {
            // 修改
            EmpWorkRequireUpdateDTO requireUpdateDTO = empWorkRequireAddDTO.to(EmpWorkRequireUpdateDTO.class);
            requireUpdateDTO.setId(requireVO.getId());

            update(requireUpdateDTO, tokenUser);
            return selectById(requireVO.getId(), tokenUser.getSiteId());
        }
        // 转DO
        EmpWorkRequireDO empWorkRequireDO = empWorkRequireAddDTO.to(EmpWorkRequireDO.class);
        // 保存
        empWorkRequireDO = save(empWorkRequireDO, tokenUser.getSiteId(), tokenUser.getUserId());
        return empWorkRequireDO.to(EmpWorkRequireVO.class);
    }

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public int update(EmpWorkRequireUpdateDTO empWorkRequireUpdateDTO, TokenUser tokenUser) {
        //转DO
        EmpWorkRequireDO empWorkRequireDO = empWorkRequireUpdateDTO.to(EmpWorkRequireDO.class);
        //根据主键更新，只更新非null值
        return updateByIdSelective(empWorkRequireDO, tokenUser.getSiteId(), tokenUser.getUserId());
    }

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public int deleteByIds(TokenUser tokenUser, String... empWorkRequireIds) {
        return logicalDeleteByIds(tokenUser.getSiteId(), tokenUser.getUserId(), (Object[]) empWorkRequireIds);
    }


    @Override
    public EmpWorkRequireVO selectById(String empWorkRequireId, String siteId) {
        EmpWorkRequireDO empWorkRequireDO = selectDOById(empWorkRequireId, siteId);
        if (empWorkRequireDO == null) {
            return null;
        }
        return empWorkRequireDO.to(EmpWorkRequireVO.class);
    }

    @Override
    public List<EmpWorkRequireListVO> select(EmpWorkRequireQuery empWorkRequireQuery, String siteId) {
        List<EmpWorkRequireDO> empWorkRequireDOList = selectDO(empWorkRequireQuery, siteId);
        if(CollectionUtils.isEmpty(empWorkRequireDOList)) {
            return empWorkRequireDOList == null ? null : new ArrayList<>();
        }
        return empWorkRequireDOList.stream()
                .map(empWorkRequireDO -> empWorkRequireDO.to(EmpWorkRequireListVO.class))
                .collect(Collectors.toList());
    }

    @Override
    public int selectCount(EmpWorkRequireQuery empWorkRequireQuery, String siteId) {
        Example example = buildExample(empWorkRequireQuery,siteId);
        return empWorkRequireDAO.selectCountByExample(example);
    }

    @Override
    public Page<EmpWorkRequireListVO> selectPage(EmpWorkRequireQuery empWorkRequireQuery, String siteId) {
        Example example = buildExample(empWorkRequireQuery,siteId);
        Page<EmpWorkRequireDO> page = empWorkRequireDAO.selectPageByExample(example,
                empWorkRequireQuery.getPageNo(),
                empWorkRequireQuery.getPageSize());

        return page.to(EmpWorkRequireListVO.class);
    }

    @Override
    public EmpWorkRequireDO selectDOById(String empWorkRequireId, String siteId) {
        return listById(empWorkRequireId, siteId);
    }

    @Override
    public List<EmpWorkRequireDO> selectDO(EmpWorkRequireQuery empWorkRequireQuery, String siteId) {
        Example example = buildExample(empWorkRequireQuery,siteId);
        return empWorkRequireDAO.selectByExample(example);
    }

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public EmpWorkRequireVO selectByCompanyAndType(String companyId, String requireType, TokenUser tokenUser) {
        EmpWorkRequireVO requireVO = findByCompanyAndType(companyId, requireType, tokenUser.getSiteId());
        if (Objects.isNull(requireVO)) {
            CompanyDO company = companyService.selectDOById(companyId, tokenUser.getSiteId());
            if (Objects.isNull(company)) {
                return null;
            }
            // 没有初始化一条
            EmpWorkRequireAddDTO requireAddDTO = new EmpWorkRequireAddDTO();
            requireAddDTO.setCompanyId(companyId);
            requireAddDTO.setRequireType(requireType);

            requireVO = save(requireAddDTO, tokenUser);
        }
        return requireVO;
    }

    /**
     * 根据公司id和类型查询所需信息
     *
     * @param companyId   公司id
     * @param requireType 类型
     * @param siteId      站点
     * @return 所需信息
     */
    private EmpWorkRequireVO findByCompanyAndType(String companyId, String requireType, String siteId) {
        Example example = new Example(EmpWorkRequireDO.class);
        example.and()
                .andEqualTo("companyId", companyId)
                .andEqualTo("requireType", requireType)
                .andEqualTo("valid", true)
                .andEqualTo("siteId", siteId);

        EmpWorkRequireDO requireDO = empWorkRequireDAO.selectOneByExample(example);
        if (Objects.isNull(requireDO)) {
            return null;
        }
        return requireDO.to(EmpWorkRequireVO.class);
    }


    /**
     * 根据查询参数，构建example

     * @param empWorkRequireQuery 查询参数
     * @param siteId 所属站点id
     * @return example
     */
    private Example buildExample(EmpWorkRequireQuery empWorkRequireQuery, String siteId) {
        Example example = new Example(EmpWorkRequireDO.class);
        example.and()
                .andEqualTo("valid", true)
                .andEqualTo("siteId", siteId);
        if (empWorkRequireQuery.getCompanyId() != null) {
            example.and().andEqualTo("companyId", empWorkRequireQuery.getCompanyId());
        }
        if (empWorkRequireQuery.getRequireType() != null) {
            example.and().andEqualTo("requireType", empWorkRequireQuery.getRequireType());
        }
        if (empWorkRequireQuery.getCompany() != null) {
            example.and().andEqualTo("company", empWorkRequireQuery.getCompany());
        }
        if (empWorkRequireQuery.getPosition() != null) {
            example.and().andEqualTo("position", empWorkRequireQuery.getPosition());
        }
        if (empWorkRequireQuery.getStartTime() != null) {
            example.and().andEqualTo("startTime", empWorkRequireQuery.getStartTime());
        }
        if (empWorkRequireQuery.getEndTime() != null) {
            example.and().andEqualTo("endTime", empWorkRequireQuery.getEndTime());
        }
        if (empWorkRequireQuery.getLeaveReason() != null) {
            example.and().andEqualTo("leaveReason", empWorkRequireQuery.getLeaveReason());
        }
        if (empWorkRequireQuery.getWitName() != null) {
            example.and().andEqualTo("witName", empWorkRequireQuery.getWitName());
        }
        if (empWorkRequireQuery.getWitPhone() != null) {
            example.and().andEqualTo("witPhone", empWorkRequireQuery.getWitPhone());
        }
        // 排序
        ExampleKit.setExampleOrder(example,empWorkRequireQuery.getOrders());
        return example;
    }
}




